const fs = require('fs')
const ora = require('ora')
const path = require('path')
const program = require('commander')
const inquirer = require('inquirer')
const superagent = require('superagent')
const { prefix } = require('./utils')

const machineIdSync  = require('node-machine-id')

const loginSpinner = ora('获取项目中...')
const loginSiteSpinner = ora('登录项目中...')

module.exports = async () => {
  try {
    const account = await inquirer
      .prompt([{
        type: 'input',
        name: 'userName',
        message: '请输入用户名'
      }, {
        type: 'password',
        name: 'password',
        message: '请输入密码'
      }])

    loginSpinner.start()
    const loginRes = await superagent
      .post('/Site5ug/login', account)
      .use(prefix)

    loginSpinner.stop()

    const {
      status: loginStatus,
      result: loginResult
    } = loginRes.body

    if (loginStatus !== 1) {
      console.log('账号或密码错误！')
      return
    }

    const { projectId } = await inquirer
      .prompt({
        type: 'list',
        name: 'projectId',
        message: '请选择项目',
        choices: loginResult.map(item => {
          return {
            name: item.companyName,
            value: item.projectId
          }
        })
      })

    loginSiteSpinner.start()
    account.machineId=machineIdSync.machineIdSync()
    const loginSiteRes = await superagent
      .post('/Site5ug/LoginSite', {
        ...account,
        projectId
      })
      .use(prefix)

    loginSiteSpinner.stop()

    const {
      status: loginSiteStatus,
      result: loginSiteResult,
      message: loginSiteMessage
    } = loginSiteRes.body

    if (loginSiteStatus === 1) {
      fs.writeFileSync(
        path.join(__dirname, '../.site.json'),
        JSON.stringify(loginSiteResult, null, 2)
      )
      const { companyName, projectId } = loginSiteResult
      console.log(`登录成功，公司名称：${companyName}，项目ID：${projectId}`)
    } else {
      console.log(loginSiteMessage || '登录失败，请确认账号密码后重试')
    }
  } catch (err) {
    loginSpinner.stop()
    loginSiteSpinner.stop()
    if (program.debug) console.error(err)
    console.log('登录失败，请稍后重试')
  }
}
